package route

import (
	"fmt"
	"io"
	"os"

	"github.com/go-kratos/kratos/v2/transport/http"
	"github.com/xuri/excelize/v2"
)

type File struct {
}

func NewFileServer() File {
	return File{}
}
func (fl File) InitRoute(route *http.Router) {
	g := route.Group("/file")
	g.POST("/download", fl.downloadFile)
	g.POST("/upload", fl.uploadFile)
	g.GET("/health", func(context http.Context) error {
		fmt.Println("file health")
		context.Response().Write([]byte("health"))
		return nil
	})
}
func (fl File) downloadFile(ctx http.Context) error {
	f := excelize.NewFile()
	index, err := f.NewSheet("Sheet2")
	if err != nil {
		panic(err)
	}
	f.SetCellValue("Sheet2", "A2", "Hello world.")
	f.SetCellValue("Sheet1", "B2", 100)
	f.SetActiveSheet(index)
	disposition := fmt.Sprintf("attachment; filename=%s", "demo.xlsx")
	ctx.Response().Header().Set("Content-Type", "application/vnd.openxmlformats")
	ctx.Response().Header().Set("Content-Disposition", disposition)
	ctx.Response().Header().Set("Access-Control-Expose-Headers", "Content-Disposition")
	return f.Write(ctx.Response())
}
func (fl File) uploadFile(ctx http.Context) error {
	req := ctx.Request()

	fileName := req.FormValue("name")
	file, handler, err := req.FormFile("file")
	if err != nil {
		return err
	}
	defer file.Close()

	f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0o666)
	if err != nil {
		return err
	}
	defer f.Close()
	_, _ = io.Copy(f, file)

	return ctx.String(200, "File "+fileName+" Uploaded successfully")
}
